package com.yanqu.road.server.gameplayer.module.smallgame;

import com.yanqu.road.entity.config.smallgame.SmallGameConfig;
import com.yanqu.road.entity.config.smallgame.SmallGameType;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.smallgame.UserSmallGameStageData;
import com.yanqu.road.logic.bussiness.player.UserSmallGameBusiness;
import com.yanqu.road.pb.smallgame.SmallGameProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.passRoad.PassRoadModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.smallgame.stage.SmallGameStageInterface;
import com.yanqu.road.server.manger.config.*;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class SmallGameModule extends GeneralModule {
    private static Logger logger = LogManager.getLogger(SmallGameModule.class.getName());

    public SmallGameModule(GamePlayer player) {
        super(player);
    }

    private Map<Integer, UserSmallGameStageData> userSmallGameStageMap;

    private boolean isLoadDB = false;

    @Override
    public boolean loadData() {
        if (this.isLoadDB) {
            return true;
        }

        userSmallGameStageMap = UserSmallGameBusiness.getUserSmallGameStageData(player.getUserId());
        initUserData();

        this.isLoadDB = true;
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public void afterLogin() {
        if (!isSystemOpen()) {
            return;
        }
        this.syncAllMessage();
    }

    public void initSystem() {
        if (!isSystemOpen()) {
            return;
        }
        this.loadData();
        this.syncAllMessage();
    }

    @Override
    public boolean saveData() {
        if (!isSystemOpen()) {
            return false;
        }

        for (UserSmallGameStageData stageData : userSmallGameStageMap.values()) {
            if (stageData.isInsertOption()) {
                stageData.setModifyTime(DateHelper.getCurrentSecond());
                UserSmallGameBusiness.addUserSmallGameStageData(stageData);
            } else if (stageData.isUpdateOption()) {
                stageData.setModifyTime(DateHelper.getCurrentSecond());
                UserSmallGameBusiness.updateUserSmallGameStageData(stageData);
            }
        }
        return true;
    }

    public boolean isSystemOpen() {
        return SystemOpenMgr.systemOpen(player, eSystemId.SmallGame.getValue());
    }

    private void initUserData() {
        if (null == userSmallGameStageMap) {
            userSmallGameStageMap = new ConcurrentHashMap<>();
        }
    }

    private void syncAllMessage() {
        SmallGameProto.SmallGameSyncMsg.Builder syncMsg = SmallGameProto.SmallGameSyncMsg.newBuilder();
        for (UserSmallGameStageData stageData : userSmallGameStageMap.values()) {
            SmallGameProto.SmallGameStageTemp.Builder stageBuilder = SmallGameProto.SmallGameStageTemp.newBuilder();
            stageBuilder.setType(stageData.getType());
            stageBuilder.addAllStageLevelPass(stageData.getStageLevelPass());
            syncMsg.addStageList(stageBuilder);
        }
        player.sendPacket(Protocol.U_SMALLGAME_DATA_SYNC, syncMsg);
    }


    public SmallGameProto.SmallGameChallengeRespMsg.Builder challengeSuccessCheck(SmallGameProto.SmallGameChallengeSuccessReqMsg reqMsg) {
        SmallGameProto.SmallGameChallengeRespMsg.Builder respMsg = SmallGameProto.SmallGameChallengeRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setType(reqMsg.getType());
        try {
            int smallGameType = reqMsg.getType();
            SmallGameConfig config = SmallGameConfigMgr.getSmallGameBaseConfig(smallGameType, reqMsg.getStageId());

            int ret = startCheck(reqMsg.getType(), reqMsg.getStageId());
            if (0 != ret) {
                return respMsg.setRet(ret);
            }

            SmallGameStageInterface stage = SmallGameConfigMgr.getStage(config);
            if (null == stage) {
                return respMsg.setRet(GameErrorCode.E_SMALLGAME_CONFIG_NOT_FOUND);
            }
            ret = stage.verifyOperation(reqMsg);
            if (0 != ret) {
                return respMsg.setRet(ret);
            }

            UserSmallGameStageData stageData = getUserStageData(smallGameType);
            if (null == stageData) {
                stageData = new UserSmallGameStageData();
                stageData.setUserId(player.getUserId());
                stageData.setType(smallGameType);
                stageData.setStageLevelPass(new ArrayList<>());
                stageData.setModifyTime(DateHelper.getCurrentSecond());
                stageData.setInsertOption();
                userSmallGameStageMap.put(smallGameType, stageData);
            }

            stageData.addStageLevelPass(config.getLevel());

            respMsg.setNowStageId(config.getId());
            respMsg.setReward(config.getReward());

            this.player.getModule(CurrencyModule.class).addCurrency(config.getReward(), eLogMoneyType.SmallGame, stage.getLogMoneyType());
            return respMsg;
        } catch (Exception e) {

        } finally {
            return respMsg;
        }
    }

    public int startCheck(int type, int stageId) {
        SmallGameConfig config = SmallGameConfigMgr.getSmallGameBaseConfig(type, stageId);
        if (null == config) {
            return GameErrorCode.E_SMALLGAME_CONFIG_NOT_FOUND;
        }

        if (config.getLevel() == 0) {
            return GameErrorCode.E_SMALLGAME_CONFIG_NOT_FOUND;
        }

        int passId = player.getModule(PassRoadModule.class).getUserPassRoad().getPassId();
        if (config.getUnlock() >= passId) {
            return GameErrorCode.E_SMALLGAME_PASSID_NOT_ENOUGH;
        }

        UserSmallGameStageData stageData = getUserStageData(type);
        if (null != stageData) {
            if (config.getLevel() > 1) {
                if (!stageData.getStageLevelPass().contains(config.getLevel() - 1)) {
                    //上一关未通关
                    return GameErrorCode.E_SMALLGAME_PRESTAGE_NOT_PASS;
                }
            }

            if (stageData.getStageLevelPass().contains(config.getLevel())) {
                //重复通关
                return GameErrorCode.E_SMALLGAME_STAGE_ALREADY_PASS;
            }
        } else if (config.getLevel() != 1) {
            //首关必须是第一关
            return GameErrorCode.E_SMALLGAME_PRESTAGE_NOT_PASS;
        }
        player.notifyListener(eGamePlayerEventType.SmallGamePlayerTime.getValue(), 1);

        return 0;
    }

    public UserSmallGameStageData getUserStageData(int type) {
        return userSmallGameStageMap.get(type);
    }

    public void rePlaySmallGame(int type, int stageId){
        SmallGameConfig config = SmallGameConfigMgr.getSmallGameBaseConfig(type, stageId);
        if (null == config) {
            return;
        }

        if (config.getLevel() == 0) {
            return;
        }

        int passId = player.getModule(PassRoadModule.class).getUserPassRoad().getPassId();
        if (config.getUnlock() >= passId) {
            return;
        }

        UserSmallGameStageData stageData = getUserStageData(type);
        if (!stageData.getStageLevelPass().contains(config.getLevel())){
            return;
        }

        //这个方法只为了这一行代码
        player.notifyListener(eGamePlayerEventType.SmallGamePlayerTime.getValue(), 1);
    }

}
